package com.tongzhan.service.impl;

import com.tongzhan.base.PageInfo;
import com.tongzhan.base.Return;
import com.tongzhan.data.vo.ActivityDetailsVO;
import com.tongzhan.data.vo.ActivityVO;
import com.tongzhan.data.vo.PicVO;
import com.tongzhan.entity.religion.Activity;
import com.tongzhan.entity.religion.ModuleSign;
import com.tongzhan.entity.religion.Site;
import com.tongzhan.file.FileGenerate;
import com.tongzhan.repository.religion.ActivityRepository;
import com.tongzhan.repository.religion.ModuleSignRepository;
import com.tongzhan.repository.religion.SiteRepository;
import com.tongzhan.service.ActivityService;
import com.tongzhan.utils.SnowFlakeUtils;
import com.tongzhan.utils.ThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class ActivityServiceImpl implements ActivityService {

    private SiteRepository siteRepository;

    private ActivityRepository activityRepository;

    private ModuleSignRepository signRepository;

    @Autowired
    private void setSiteRepository(SiteRepository siteRepository) {
        this.siteRepository = siteRepository;
    }

    @Autowired
    private void setActivityRepository(ActivityRepository activityRepository) {
        this.activityRepository = activityRepository;
    }

    @Autowired
    private void setModuleSignRepository(ModuleSignRepository signRepository) {
        this.signRepository = signRepository;
    }

    @Override
    public Return uploadActivity(Activity activity) {
        //生成活动编码
        SnowFlakeUtils snow = new SnowFlakeUtils(4,6);
        activity.setActivityCode(String.valueOf(snow.nextId()));
        //场所信息
        Site site = siteRepository.findByPrimaryKey(activity.getSiteCode());
        if (site != null) {
            activity.setSiteName(site.getSiteName());
            activity.setStreetName(site.getStreetName());
            activity.setReligionCode(site.getReligionCode());
            activity.setReligionName(site.getReligionName());
        }
        //生成图片信息
        FileGenerate.generate(activity.getPicture(), activity.getUserName());
        activity.setCreateTime(LocalDateTime.now());
        activityRepository.insert(activity);
        //新增活动民宗局角标提醒
        List<ModuleSign> signList = signRepository.findAll(new Query().addCriteria(Criteria.where("DutiesCode").is("01")));
        if (!CollectionUtils.isEmpty(signList)) {
            for (ModuleSign sign : signList) {
                //活动模块角标加一
                sign.setActivity(sign.getActivity() + 1);
                signRepository.updateByPrimaryKey(sign);
            }
        }
        return new Return(Return.SUCCESS, "操作成功");
    }

    @Override
    public Return getActivityList(String userId, String siteCode, String religionCode, String time, Integer page, Integer size) {
        //查询条件
        Query query = new Query();
        query.with(Sort.by(Sort.Direction.DESC, "CreateTime"));
        //获取当前登录用户信息
        ThreadLocalUtil.AdminThreadLocal threadLocal = ThreadLocalUtil.getThreadLocal();
        //权限编码
        String dutiesCode = threadLocal.getDutiesCode();
        if (ThreadLocalUtil.STREET_CODE.equals(dutiesCode)) {
            //镇街道
            query.addCriteria(Criteria.where("StreetCode").is(threadLocal.getStreetCode()));
        } else if (ThreadLocalUtil.VILLAGE_CODE.equals(dutiesCode)) {
            //村社区
            query.addCriteria(Criteria.where("VillageCode").is(threadLocal.getVillageCode()));
        }
        if (StringUtils.isNotEmpty(time)) {
            try {
                time = time + "-01";
                //日期解析
                DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
                LocalDate date = LocalDate.parse(time, dtf);
                query.addCriteria(Criteria.where("StartTime").lte(date.with(TemporalAdjusters.lastDayOfMonth()))
                        .orOperator(Criteria.where("EndTime").gte(date.with(TemporalAdjusters.firstDayOfMonth()))));
            } catch (Exception e) {
                return new Return(Return.FAIL, "日期格式应为 2020-01");
            }
        }
        if (StringUtils.isNotEmpty(siteCode)) {
            query.addCriteria(Criteria.where("SiteCode").is(siteCode));
        }
        if (StringUtils.isNotEmpty(religionCode)) {
            query.addCriteria(Criteria.where("ReligionCode").is(religionCode));
        }
        Page<Activity> activities = activityRepository.findPage(query, PageRequest.of(page - 1, size));
        List<Activity> activityList = activities.getContent();
        //VO
        List<ActivityVO> vos = new ArrayList<>();
        if (!CollectionUtils.isEmpty(activityList)) {
            for (Activity activity : activityList) {
                ActivityVO vo = new ActivityVO();
                vo.setActivityCode(activity.getActivityCode());
                vo.setTitle(activity.getTitle());
                vo.setSiteName(activity.getSiteName());
                vo.setStartTime(activity.getStartTime());
                vo.setEndTime(activity.getEndTime());
                vos.add(vo);
            }
        }
        //重置活动模块角标
        ModuleSign sign = signRepository.findByPrimaryKey(userId);
        if (sign != null) {
            sign.setActivity(0L);
            signRepository.updateByPrimaryKey(sign);
        }
        //分页
        PageInfo pageInfo = new PageInfo();
        pageInfo.setPage(page);
        pageInfo.setSize(vos.size());
        pageInfo.setTotal(activities.getTotalElements());
        //分装返回数据
        Map<String, Object> map = new HashMap<>();
        map.put("activityList", vos);
        map.put("pageInfo", pageInfo);
        return new Return(map);
    }

    @Override
    public Return activityDetails(String activityCode) {
        //活动
        Activity activity = activityRepository.findByPrimaryKey(activityCode);
        //VO
        ActivityDetailsVO vo = new ActivityDetailsVO();
        if (activity != null) {
            vo.setActivityCode(activity.getActivityCode());
            vo.setTitle(activity.getTitle());
            vo.setContent(activity.getDetail());
            vo.setSiteName(activity.getSiteName());
            vo.setNumber(activity.getNumber());
            vo.setReligionName(activity.getReligionName());
            vo.setStartTime(activity.getStartTime());
            vo.setEndTime(activity.getEndTime());
            List<PicVO> picList = new ArrayList<>();
            //图片
            String picture = activity.getPicture();
            if (StringUtils.isNotEmpty(picture)) {
                String[] files = picture.split(",");
                for (String file : files) {
                    PicVO picVO = new PicVO();
                    picVO.setPath(file);
                    picList.add(picVO);
                }
            }
            vo.setPicList(picList);
        }
        return new Return(vo);
    }

    @Override
    public Return deleteActivity(String activityCode) {
        long res = activityRepository.deletePrimaryKey(activityCode);
        if (res <= 0) {
            return new Return(Return.FAIL, "删除失败");
        }
        return new Return(Return.SUCCESS, "删除成功");
    }

    @Override
    public Return update(String activityCode, String title, String content, Long number, String startTime, String endTime, String picture) {
        Activity activity = activityRepository.findByPrimaryKey(activityCode);
        if (activity == null) {
            return new Return(Return.FAIL, "活动记录数据不存在");
        }
        //日期解析
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate start;
        LocalDate end;
        try {
            start = LocalDate.parse(startTime, dtf);
            end = LocalDate.parse(endTime, dtf);
        } catch (Exception e) {
            return new Return(Return.FAIL, "日期格式不正确");
        }
        activity.setStartTime(start);
        activity.setEndTime(end);
        activity.setTitle(title);
        activity.setDetail(content);
        activity.setPicture(picture);
        activity.setNumber(number);
        activityRepository.updateByPrimaryKey(activity);
        return new Return(Return.SUCCESS, "修改成功");
    }
}
